import os
import sys
import gdal
import numpy as np
from gdalconst import *
from constants import __BAND__
from utilities import __get_bounding_coor__
from utilities import __get_log_time_format__

class ResampleNPP:
	
	# init
	def __init__(self):
		self.uncorrect_fname = ""
		self.correct_fname = ""
		self.vrt_fname = ""
		self.iband = ""
		self.resimage = ""

	# convert dataset to image file containing GCPs
	def __hdf5_to_image__(self, h5file, band):
		lad = "HDF5:" + h5file + "://All_Data/VIIRS-MOD-GEO-TC_All/Latitude"
		lod = "HDF5:" + h5file + "://All_Data/VIIRS-MOD-GEO-TC_All/Longitude"
		coors = __get_bounding_coor__(lad, lod)
		# write corners to file
		corfile = h5file[:-3] + "_550_corner.txt"
		fi = open(corfile, "w")
		fi.write("{0} {1}, {2} {3}, {4} {5}, {6} {7}".format(str(coors[0]), str(coors[3]), str(coors[0]), str(coors[2]), str(coors[1]), str(coors[2]), str(coors[1]), str(coors[3])))
		fi.close()

		out = h5file[:-3] + "_" + str(band) + ".raw"
		self.iband = h5file[:-3] + "_" + str(band)
		#command = "gdal_translate -of GTiff HDF5:\"" + h5file + "\"://All_Data/VIIRS-LST-EDR_All/LandSurfaceTemperature" + " " + out
		command = "gdal_translate -of GTiff HDF5:\"" + h5file + "\"://All_Data/VIIRS-SST-EDR_All/BulkSST" + " " + out
		status = os.system(command)
		if status == 0:
			self.uncorrect_fname = out
			print out
			return 1
		return 0

	# correct GCPs points
	def __correct_GCPs__(self):
		print(self.uncorrect_fname)
		print "Processing correct GCPs..."
		aot_dataset = gdal.Open(self.uncorrect_fname, GA_ReadOnly)	
		if aot_dataset is None:
			print('Couldnt open file: {0}\n'.format(self.uncorrect_fname))
			return 0
		aot_data = aot_dataset.ReadAsArray()
		cols = aot_dataset.RasterXSize
		rows = aot_dataset.RasterYSize
	
		# get GCP points	
		gcps = aot_dataset.GetGCPs()
		refine_gcps = []
		for gcp in gcps:
			if gcp.GCPX != 0 and gcp.GCPX != -999.3 and gcp.GCPY != 0 and gcp.GCPY != -999.3:
				gcp.GCPX = gcp.GCPX - 180
				refine_gcps.append(gcp)
		# create output maxtri
		aot_datal = np.zeros((rows, cols), dtype=np.float32)
		#lst_scale = float(0.0025455155)
		#lst_offset = float(183.2)
		aot_scale = float(0.00083934865)
		aot_offset = float(265.0)

		# calculate aot value with offset and scale
		"""for i in range(0, rows):
			for j in range(0, cols):
				if aot_data[i,j] <= 0 or aot_data[i,j] > 65000:
					aot_datal[i,j] = 0
				else:
					aot_datal[i,j] = aot_scale*aot_data[i,j] + aot_offset"""
		# create output file
		output_filename = self.uncorrect_fname[:-4] + "_recorrect.rec"
		gtiff = gdal.GetDriverByName('GTiff')
		output = gtiff.Create(output_filename, cols, rows, 1, gdal.GDT_Float32)
		if output is None:
			print("[{0}] can't create corrected GCP file: {1}\n".format(__get_log_time_format__(), output_filename))
			return 0
		output.SetGCPs(tuple(refine_gcps), output.GetProjection())
		output.GetRasterBand(1).WriteArray(aot_datal)
		
		self.correct_fname = output_filename
		print self.correct_fname
		self.uncorrect_fname = ""
		print "End  correct GCPs..."
		return 1

	# resample 
	def __resample__(self):
		# make vrt file
		print "Processing resample..."
		if self.correct_fname != "":
			self.vrt_fname = self.correct_fname[:-4] + ".vrt"
			os.system("gdal_translate -of VRT " + self.correct_fname + " " + self.vrt_fname)
			self.correct_fname = ""
		# create PNG image and grid
		if self.vrt_fname != "":
			# create PNG
			resampleimage = self.vrt_fname[:-4] + "sst_resample_.tif"
			#os.system("gdalwarp -of GTiff -tps {0} {1} >> {2}".format(self.vrt_fname, tiffull, log))
			#os.system("gdalinfo {0} > {1}".format(tiffull, metadata))
			#os.system("gdal_translate -of PNG -ot Byte {0} {1} >> {2}".format(tiffull, pngori, log))
			#os.system("gdal_translate -of PNG -ot Byte -outsize 500 450 {0} {1} >> {2}".format(tiffull, pnglarge, log))
			# create grid 
			os.system("gdalwarp -t_srs '+proj=longlat +datum=WGS84' -tps -ot Float32 -wt Float32 -te 100.1 6.4 111.8 25.6 -tr 0.05 -0.05 -r cubic -srcnodata 0.0 -dstnodata 0.0 -overwrite -multi " + self.vrt_fname + " " + resampleimage)
			self.iband = ""	
			self.vrt_fname = ""
			print "End resample"
			return 1
		return 0

	# do every thing
	def __do_everything__(self, h5file, band):
		s = self.__hdf5_to_image__(h5file, band)
		if s == 0:
			return ""
		s = self.__correct_GCPs__()
		if s == 0:
			return ""
		s = self.__resample__()
		if s == 0:
			return ""
		return self.resimage

	# resample hdf5 files
	def __resample_hdf5_in_directory__(self, log, directory):
		os.chdir(directory)
		h5files = [f for f in os.listdir(".") if os.path.isfile(f) and f.endswith('.h5')]
		for f in h5files:
			s = self.__do_everything__(f, __BAND__)
			if s == "":
				return 0
		rawfiles = [f for f in os.listdir(".") if os.path.isfile(f) and f.endswith('.raw')]
		for f in rawfiles:
			os.remove(f)
		recfiles = [f for f in os.listdir(".") if os.path.isfile(f) and f.endswith('.rec')]
		for f in recfiles:
			os.remove(f)
		vrtfiles = [f for f in os.listdir(".") if os.path.isfile(f) and f.endswith('.vrt')]
		for f in vrtfiles:
			os.remove(f)
		xmlfiles = [f for f in os.listdir(".") if os.path.isfile(f) and f.endswith('.xml')]
		for f in xmlfiles:
			os.remove(f)
		return 1

res = ResampleNPP()
res.__resample_hdf5_in_directory__("a,txt","/home/phamha/Desktop/npp/")